package com.beiing.tianshuai.tianshuai.huodong.view;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.NewDiscoveryPublishActivity;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.EventTypesBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.entity.VersionInfoBean;
import com.beiing.tianshuai.tianshuai.huodong.AllEventsFragment;
import com.beiing.tianshuai.tianshuai.huodong.adapter.MyPagerAdapter;
import com.beiing.tianshuai.tianshuai.huodong.presenter.HuoDongPresenter;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.service.UpdateAppService;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CheckVersionDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.DownLoadProgressDialog;
import com.flyco.tablayout.SlidingTabLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by magikliu on 2017/7/9.
 */

public class HuoDongActivity extends BaseActivity implements HuoDongViewImpl {

    @BindView(R.id.toolbar_tv_title)
    TextView toolbarTvTitle;
    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_iv_publish)
    ImageView toolbarIvPublish;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.sliding_tab)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.activity_fragment_container)
    ViewPager mViewPager;
    @BindView(R.id.rv_request_fail)
    RelativeLayout rvRequestFail;
    @BindView(R.id.tv_refresh)
    TextView tvRefresh;

    public static final String TAG = "HuoDongFragment";
    private boolean hasLoadedOnce;
    private boolean isFirstLoad = true;                 // 是否第一次加载
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private HuoDongPresenter mPresenter;
    private File mFile;
    private String mAppName;
    private DownLoadProgressDialog mProgressDialog;
    private int mFileLength;
    private int retryConnect = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_huodong;
    }

    @Override
    protected void init() {
        ((AppCompatActivity) mContext).setSupportActionBar(toolbar);
        if (!hasLoadedOnce) {
            initTabLayout();
        }
        initPresenter();
        initListener();
        initDialog();
    }


    private void initPresenter() {
        mPresenter = new HuoDongPresenter(this);
        mPresenter.getTabTitles();
    }

    private void initTabLayout() {
        toolbarTvTitle.setText("活动");
    }

    public void initListener() {
        toolbarIvBack.setVisibility(View.VISIBLE);
        toolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        toolbarIvPublish.setVisibility(View.VISIBLE);
        toolbarIvPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uid = UserInfoBean.getUid(mContext);
                if (!TextUtils.isEmpty(uid)) {
                    String attestation = UserInfoBean.getAttestation(mContext);
                    switch (attestation) {
                        case "4":
                            Intent intent = new Intent(mContext, NewDiscoveryPublishActivity.class);
                            intent.putExtra("type", 0);
                            startActivity(intent);
                            break;
                        case "2":
                        case "3":
                        default:
                            showShortText("“组织认证/企业认证”用户才可以发布噢~");
                            break;
                    }
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void showProgress() {
        if (isFirstLoad) {
            CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
            isFirstLoad = false;
        }
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(EventTypesBean bean) {
        mViewPager.setVisibility(View.VISIBLE);
        rvRequestFail.setVisibility(View.GONE);

        int typeNum = bean.getData().getNumber().size();
        String[] tabTitles = new String[typeNum + 1];
        for (int i = 0; i < typeNum; i++) {
            tabTitles[i + 1] = bean.getData().getNumber().get(i).getName();
        }
        tabTitles[0] = "全部活动";
        String[] ids = new String[typeNum];
        for (int i = 0; i < typeNum; i++) {
            ids[i] = bean.getData().getNumber().get(i).getId();
        }
        mFragments.add(new AllEventsFragment());
        for (int i = 0; i < tabTitles.length - 1; i++) {
            mFragments.add(EventsCommonFragment.newInstance(ids[i]));
        }
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), mFragments, tabTitles);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(3);
        mTabLayout.setViewPager(mViewPager);
        hasLoadedOnce = true;
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        if (retryConnect < 5) {
            retryConnect++;
            mPresenter.getTabTitles();
        } else {
            retryConnect = 1;
            mViewPager.setVisibility(View.GONE);
            rvRequestFail.setVisibility(View.VISIBLE);
            rvRequestFail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
                    mPresenter.getTabTitles();
                }
            });
        }
    }

    /**
     * 检查服务器上是否有新版本的应用更新
     *
     * @param bean 版本信息
     */
    @Override
    public void getVersionInfo(VersionInfoBean bean) {
        String info = bean.getData().getNumber().toString();
        LogUtils.i(info, TAG);
        VersionInfoBean.DataBean.NumberBean versionBean = bean.getData().getNumber();
        int versionCode = Integer.valueOf(versionBean.getVersioncode());
        String versionName = versionBean.getVersionname();
        String description = versionBean.getDescription();
        mAppName = versionBean.getApk();
        checkUpdate(versionCode, versionName, description);
    }

    private void checkUpdate(int versionCodeNow, String versionNew, String description) {
        int versionCodeNew = 0;
        try {
            versionCodeNew = mContext.getPackageManager().getPackageInfo("com.beiing.tianshuai.tianshuai", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (versionCodeNew < versionCodeNow) {
            CheckVersionDialog dialog = new CheckVersionDialog(mContext, R.style.dialog, new CheckVersionDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm, int id) {
                    if (confirm) {
                        switch (id) {
                            case R.id.btn_update_now:
                                mProgressDialog.setCancelable(false);
                                mProgressDialog.setCanceledOnTouchOutside(false);
                                mProgressDialog.show();
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        downloadFile(); // 开始下载
                                    }
                                }).start();
                                break;
                            case R.id.btn_update_background:
                                showShortText("已转到后台下载最新版APK");
                                Intent intent = new Intent(mContext, UpdateAppService.class);
                                intent.putExtra("app_name", mAppName);
                                intent.putExtra("url", HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName);
                                mContext.startService(intent);
                                break;
                        }
                    }
                    dialog.dismiss();
                }
            }).setContent(description).setVersionName("是否升级到" + versionNew + "版本？");
            dialog.show();
        }
    }

    private void downloadFile() {
        try {
            URL url = new URL(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName);
            LogUtils.i(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName, "apkURL");
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                mFileLength = conn.getContentLength();
                mProgressDialog.setMax(mFileLength);
                String dir = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
                File apkDir = new File(dir);
                if (!apkDir.exists()) {
                    if (apkDir.mkdirs()) {
                        LogUtils.i("创建路径 “/TianShuai/天率校园/” 成功", "make dir");
                    } else {
                        LogUtils.e("创建路径 “/TianShuai/天率校园/” 失败", "make dir");
                    }
                }
                String path = dir + mAppName;
                mFile = new File(path);
                FileOutputStream fileOutputStream = new FileOutputStream(mFile);
                int length;
                int progress = 0;
                byte[] bytes = new byte[1024];
                while ((length = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, length);
                    progress += length;
                    Message msgUpdateProgress = new Message();
                    msgUpdateProgress.what = 100;
                    msgUpdateProgress.obj = progress;
                    mHandler.sendMessage(msgUpdateProgress);
                }
                inputStream.close();
                fileOutputStream.close();
                fileOutputStream.flush();
                Message msgDownloadFinish = new Message();
                msgDownloadFinish.what = 200;
                mHandler.sendMessage(msgDownloadFinish);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 100://更新dialog进度
                    int count = (int) message.obj;
                    mProgressDialog.setProgress(count);
                    int i = count / (1024 * 1024);
                    int j = mFileLength / (1024 * 1024);
                    mProgressDialog.setPercent(i + "M/" + j + "M");
                    break;
                case 200://下载完成
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    //判读版本是否在7.0以上
                    if (Build.VERSION.SDK_INT >= 24) {
                        updateMoreThan7();
                    } else {
                        updateUnderAndroid7();
                    }
                    break;
            }
            return false;
        }
    });

    private void initDialog() {
        mProgressDialog = new DownLoadProgressDialog(mContext, R.style.dialog);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
    }

    /**
     * 适配Android7版本以下安装程序
     */
    private void updateUnderAndroid7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), mAppName)),
                "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 适配Android7版本以上安装程序
     */
    private void updateMoreThan7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkURI = FileProvider.getUriForFile(mContext, "com.beiing.tianshuai.fileprovider", mFile);
        intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }
}
